<?php

namespace App\Service\Wechat;

use App\Service\Log\LogService;
use EasyWeChat\Kernel\Support\Collection;
use EasyWeChat\MiniProgram\Application;
use Exception;
use Illuminate\Support\Facades\Log;
use Psr\Http\Message\ResponseInterface;

class WechatAppService
{
    protected Application $app;
    public function __construct()
    {
        $isQh = mb_strpos(request()->path(), '/qh_mp/');
        if ($isQh) $this->app = new Application(config('wechat.qh_min_app'));
        else $this->app = new Application(config('wechat.min_app'));
    }

    /**
     * 获取openid
     * @param string $code
     * @return array|Collection|object|ResponseInterface|string
     * @throws Exception
     */
    public function getOpenId(string $code) {
        try {
            $result = $this->app->auth->session($code);
            LogService::debug(json_encode($result), '微信');
            if (!empty($result['errcode'])) {
                LogService::debug($result['errmsg'], '微信code -> openid');
                throw new Exception('登录失败', 401);
            }
            return $result;
        }catch (Exception $e) {
            Log::error($e->getMessage());
            throw new Exception('微信授权失败');
        }
    }
}
